<template>
  <div class="app-container">
    {{form}}
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电子围栏编码" prop="railCode">
        <el-input
          v-model="queryParams.railCode"
          placeholder="请输入电子围栏编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="围栏名称" prop="railName">
        <el-input
          v-model="queryParams.railName"
          placeholder="请输入围栏名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="railUserCode">
        <el-input
          v-model="queryParams.railUserCode"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:rail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:rail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:rail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="railList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="railId" />
      <el-table-column label="电子围栏编码" align="center" prop="railCode" />
      <el-table-column label="围栏名称" align="center" prop="railName" />
<!--      <el-table-column label="围栏类型" align="center" prop="railType" />-->
      <el-table-column label="围栏状态" align="center" prop="railStatus"  :formatter="formatterSex" />
<!--      <template slot-scope="scope">-->
<!--        <span v-if="scope.row.railStatus==111">驶入</span>-->
<!--        <span v-if="scope.row.railStatus==222">驶出</span>-->
<!--      </template>-->
      <el-table-column label="围栏路径" align="center" prop="railPath" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rail:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:rail:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电子围栏对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="电子围栏编码" prop="railCode">
          <el-input v-model="form.railCode" placeholder="请输入电子围栏编码" />
        </el-form-item>
        <el-form-item label="围栏名称" prop="railName">
          <el-input v-model="form.railName" placeholder="请输入围栏名称" />
        </el-form-item>
<!--        <el-form-item label="围栏路径" prop="railPath">-->
<!--&lt;!&ndash;          <el-input v-model="form.railPath" type="textarea" placeholder="请输入内容" />&ndash;&gt;-->
<!--          <el-button @click="toMap">绘制地图</el-button>-->
<!--        </el-form-item>-->

        <el-form-item>
          <div style="margin-top: 5px">
            <div style="height:340px;">
              <div id="all" style="height:30%">
                <div id="allmap">
                  <div id="containerIp">
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="input-item">
            <input type="button" class="btn" value="开始绘制" id="start" @click="startDrawPolygon()" />
            <input type="button" class="btn" value="清空" id="pause" @click="clearPolygon()" />
            <input type="button" class="btn" value="结束并保存" id="resume" @click="stopAndSave()" />
            <input type="button" class="btn" value="重新绘制" id="stop" @click="redrawPolygon()" />
          </div>

        </el-form-item>




      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>





</template>

<script>
import { listRail, getRail, delRail, addRail, updateRail } from "@/api/system/rail";

export default {
  name: "Rail",
  data() {
    return {

      show:false,
      ws: null,
      receiveIp:'',
      map: null,
      marker:null,// 地理编码与逆地理编码类，用于地址描述与坐标之间的转换
      startAutoComplete: null,
      startPlaceSearch: null,
      positionPicker:null,
      startSeacrh:[],
      stratInfo:{},

      thisPosition: {
        location: '',
        lng: '',
        lat: ''
      },
      mapinitCode:0,//地理编码:1;地理逆编码:2
      MapAdress:'',
      insureAdress:'',
      insureAdress2:'',
      input: '',
      mouseTool: null,
      polyType: {
        strokeColor: "red",
        strokeOpacity: 1,
        strokeWeight: 4,
        fillColor: "red",
        fillOpacity: 0.4,
        // 线样式还支持 'dashed'
        strokeStyle: "solid"
        // strokeStyle是dashed时有效
        // strokeDasharray: [30,10],
      },
      polygonList: [],
      savedPolygon: [],
      polyline:"",
      polylineEditor:"",

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电子围栏表格数据
      railList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        railCode: null,
        railName: null,
        railType: null,
        railStatus: null,
        railPath: null,
        railUserCode: null,
        railDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();

    this.$nextTick(() => {
      this.initMap();
    });

  },
  methods: {
    formatterSex(row, coumn) {
      if (row.railStatus == 1) {
        return '启用'
      }
      if (row.railStatus == 2) {
        return '停用'
      }
    },

    initMap() {
      this.map = new AMap.Map("containerIp", {
        resizeEnable: true,
        center: [114.4718, 38.082760],
        zoom: 16
      });
    },
    // TODO 开始绘画
    startDrawPolygon() {
      this.clearPolygon();
      let __this = this;
      this.map.plugin("AMap.MouseTool", function() {
        __this.mouseTool = new AMap.MouseTool(__this.map);
      });
      this.mouseTool.polygon(this.polyType);
      //TODO 监听draw事件可获取画好的覆盖物
      this.polygonList = [];
      this.mouseTool.on("draw", function(e) {
        __this.polygonList.push(e.obj);
        console.log("+++++++++  "+e.obj)
        console.log("绘制的多边形", __this.polygonList);
        __this.mouseTool.close();
      });
    },
    // TODO 结束绘画
    stopAndSave() {
      // this.mouseTool.close();
      for (let i = 0; i < this.polygonList.length; i++) {
        let op = this.polygonList[i].getOptions();
        let routePath = [];
        op.path.forEach(item => {
          routePath.push([item.lng, item.lat]);
        });
        console.log(routePath)
        let savearr = {
          path: routePath,
          strokeColor: op.strokeColor,
          strokeOpacity: op.strokeOpacity,
          fillOpacity: op.fillOpacity,
          fillColor: op.fillColor,
          zIndex: op.zIndex
        };
        this.savedPolygon=[]
        this.savedPolygon.push(savearr);
      }
      this.form.railPath= JSON.stringify(this.savedPolygon);
      this.savedPolygon=[];
    },
    // TODO 清空绘画
    clearPolygon() {
      //this.map.remove(this.polygonList);
      this.polygonList = [];
      this.map.clearMap(); // 清除地图上的所有覆盖物
    },
    // TODO 重新绘画
    // 用保存的数据重新绘制多边形并添加事件
    redrawPolygon() {
      let __this = this;
      // 用浏览器模拟数据库存取
      let savedPolygon = this.polygonList
      console.log("重绘多边形数据", savedPolygon);
      if (savedPolygon == null) return;
      for (let i = 0; i < savedPolygon.length; i++) {
        var polygon = new AMap.Polygon(savedPolygon[i]);
        this.map.add(polygon);
      }
    },
    //去地图
    toMap(){
      this.$router.push("/aaa")
    },
    /** 查询电子围栏列表 */
    getList() {
      this.loading = true;
      listRail(this.queryParams).then(response => {
        this.railList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        railId: null,
        railCode: null,
        railName: null,
        railType: null,
        railStatus: null,
        railPath: null,
        railUserCode: null,
        createTime: null,
        updateTime: null,
        railDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.railId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.$nextTick(() => {
        this.map = new AMap.Map("containerIp", {
          resizeEnable: true,
          center: [114.459779, 38.087936],
          zoom: 16
        });
      });
      this.title = "添加电子围栏";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.$nextTick(() => {
        this.map = new AMap.Map("containerIp", {
          resizeEnable: true,
          center: [114.459779, 38.087936],
          zoom: 16
        });
      });
      this.redrawPolygon()

      const railId = row.railId || this.ids
      getRail(railId).then(response => {
        this.form = response.data;
        const parse = JSON.parse(row.railPath);
        this.savedPolygon=parse;
        const path=parse[0].path
        const arr=[]
        for(var i=0;i<path.length;i++){
          arr.push([path[i][0],path[i][1]])
        }//经纬度坐标数组

        const polygon = new AMap.Polygon({
          path: arr,
          strokeColor: "green",
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: 'green',
          zIndex: 16,
        })

        this.map.add(polygon)
        this.map.setFitView([ polygon ])

        const polyEditor = new AMap.PolyEditor(this.map, polygon)
        polyEditor.open()



        polyEditor.on('addnode', function(event) {
          log.info('触发事件：addnode')
        })


        polyEditor.on('adjust', function(event) {
          log.info('触发事件：adjust')
        })

        polyEditor.on('removenode', function(event) {
          log.info('触发事件：removenode')
        })

        polyEditor.on('end', function(event) {
          log.info('触发事件： end')
          // event.target 即为编辑后的多边形对象
        })


        this.title = "修改电子围栏";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.railId != null) {
            updateRail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const railIds = row.railId || this.ids;
      this.$modal.confirm('是否确认删除电子围栏编号为"' + railIds + '"的数据项？').then(function() {
        return delRail(railIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/rail/export', {
        ...this.queryParams
      }, `rail_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


<style lang="css" scoped>
.containerIp {
  width:100%;
  height: 500px;
  position: relative;
  left: 0;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  border: 1px solid #999;
}

.search-box {
  position: absolute;
  z-index: 5;
  width: 70%;
  left: 13%;
  top: 10px;
  height: 30px;
}

.search-box input {
  float: left;
  width: 59%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
}

.search-box button {
  float: left;
  width: 20%;
  height: 10%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}

.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
#containerIp {
  width: 70%;
  height: 300px;
}

.input-card .btn {
  margin-right: 1.2rem;
  width: 9rem;
}

.input-card .btn:last-child {
  margin-right: 0;
}

html,body,#app{
  height: 100%;
  width: 100%;
}
#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 80px;
  right: 10px;
  width: 280px;
}
</style>

